package network;
import signals.*;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class UDPListener extends Thread {
	
	DatagramSocket socket;
	int port;
	byte[] buf = new byte [1024];
	ChatNI netwInt;
	
	public UDPListener(ChatNI father, int portUDP) {
		netwInt = father;
		this.port = portUDP;
		try {
	      socket = new DatagramSocket(port);
	      socket.setReceiveBufferSize(1024);
		}
		catch (SocketException e){
			System.out.println("Error creating the following UDP socket : "+port);
		}
	}
	
	public void run () {
		while (true) {
			receivePacket();
		}
	}
	
	public void receivePacket (){
		Signal s;
		DatagramPacket dP = new DatagramPacket(buf, buf.length);
		
		try {
			socket.receive(dP);
		} catch (IOException e) {
			System.out.println("Error receiving file on port : "+ port );
		}
		InetAddress addr = dP.getAddress();
		
		s = Signal.deserialize(buf, buf.length); 
		
		netwInt.receiveSignal(s, addr);
	}
	
}
